Page({
  data: {
    loading: true,
    members: [],
    selectedMemberId: null,
    recordTypes: ['血压', '血糖', '体重', '体温', '心率', '睡眠'],
    selectedType: '全部',
    records: [],
    filteredRecords: []
  },

  onLoad: function (options) {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 从参数或本地存储获取选中的成员ID
    let selectedMemberId = options.memberId;
    if (!selectedMemberId) {
      selectedMemberId = wx.getStorageSync('selectedMemberId');
      // 使用后清除，避免影响下次进入
      wx.removeStorageSync('selectedMemberId');
    }
    
    if (selectedMemberId) {
      this.setData({
        selectedMemberId: selectedMemberId
      });
      console.log('从首页接收到成员ID:', selectedMemberId);
    }
    
    // 尝试从事件通道获取数据
    try {
      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel && typeof eventChannel.on === 'function') {
        eventChannel.on('memberSelected', (data) => {
          if (data && data.memberId) {
            this.setData({
              selectedMemberId: data.memberId
            });
            console.log('从事件通道接收到成员ID:', data.memberId);
            // 重新筛选记录
            this.filterRecords();
          }
        });
      }
    } catch (error) {
      console.log('获取事件通道失败，这可能是正常的，如从tabBar页面跳转:', error);
    }
    
    this.loadMembers();
    this.loadRecords();
  },

  onShow: function () {
    // 检查是否有新的选中成员ID (优先检查，确保在加载数据前就设置好筛选条件)
    const selectedMemberId = wx.getStorageSync('selectedMemberId');
    if (selectedMemberId) {
      console.log('onShow中接收到成员ID:', selectedMemberId);
      this.setData({
        selectedMemberId: selectedMemberId
      }, () => {
        // 数据设置完成后，尝试滚动到选中成员
        // 如果成员数据已加载
        if (this.data.members && this.data.members.length > 0) {
          this.scrollToSelectedMember();
        }
      });
      wx.removeStorageSync('selectedMemberId');
    }
    
    // 页面显示时刷新数据
    this.loadMembers();
    this.loadRecords();
  },

  loadMembers: function () {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 从服务器获取家庭成员数据
    wx.request({
      url: 'http://localhost:3000/api/members',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          // 确保成员数据格式正确，每个成员都有id和name属性
          const members = res.data.data.members || [];
          const processedMembers = members.map(member => ({
            id: member.id || member._id,
            name: member.name,
            // 保留其他可能需要的属性
            ...member
          }));
          
          this.setData({
            members: processedMembers
          });
          console.log('成功加载家庭成员:', processedMembers);
          
          // 如果有选中的成员ID，滚动到对应位置
          this.scrollToSelectedMember();
        } else {
          console.error('获取家庭成员失败:', res.data.message);
          wx.showToast({
            title: res.data.message || '获取成员数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 滚动到选中的成员位置
  scrollToSelectedMember: function() {
    const { selectedMemberId, members } = this.data;
    
    if (selectedMemberId && members && members.length > 0) {
      // 查找选中成员在数组中的索引
      const index = members.findIndex(member => member.id == selectedMemberId);
      
      if (index > -1) {
        console.log(`找到选中成员，索引: ${index}, ID: ${selectedMemberId}`);
        
        // 延迟滚动，确保视图已经渲染
        setTimeout(() => {
          wx.createSelectorQuery()
            .select('.members-scroll')
            .node()
            .exec((res) => {
              if (res && res[0] && res[0].node) {
                // 计算滚动位置（每个项目宽度约为 70px + 间距）
                const scrollLeft = index * 80; // 估计的滚动距离
                res[0].node.scrollLeft = scrollLeft;
                console.log(`滚动到位置: ${scrollLeft}px`);
              }
            });
        }, 100);
      }
    }
  },

  loadRecords: function () {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    // 从服务器获取健康记录数据
    wx.request({
      url: 'http://localhost:3000/api/records',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const records = res.data.data.records || [];
          
          // 确保每条记录都有memberName
          const processedRecords = records.map(record => ({
            ...record,
            memberName: record.member ? record.member.name : '未知成员'
          }));
          
          this.setData({
            records: processedRecords,
            loading: false
          });
          
          // 应用当前筛选条件
          this.filterRecords();
          console.log('记录加载完成，应用筛选条件。当前选中成员ID:', this.data.selectedMemberId);
        } else {
          console.error('获取健康记录失败:', res.data.message);
          this.setData({ loading: false });
          wx.showToast({
            title: res.data.message || '获取记录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  selectMember: function (e) {
    const memberId = e.currentTarget.dataset.id;
    
    // 如果点击的是当前选中的成员，则取消选择
    const newSelectedId = (memberId !== null && this.data.selectedMemberId !== null && 
                          String(memberId) === String(this.data.selectedMemberId)) 
                          ? null : memberId;
    
    this.setData({
      selectedMemberId: newSelectedId
    });
    
    console.log('选择成员ID:', newSelectedId);
    this.filterRecords();
  },

  selectType: function (e) {
    const type = e.currentTarget.dataset.type
    
    this.setData({
      selectedType: type
    })
    
    this.filterRecords()
  },

  filterRecords: function () {
    const { records, selectedMemberId, selectedType } = this.data
    
    let filtered = records
    
    if (selectedMemberId !== null) {
      filtered = filtered.filter(record => {
        // 兼容不同的成员ID字段名
        const recordMemberId = record.member_id || record.memberId;
        
        // 转换为字符串进行比较，防止类型不匹配导致比较失败
        return String(recordMemberId) === String(selectedMemberId);
      });
      
      console.log(`筛选成员ID ${selectedMemberId} 的记录，结果数量: ${filtered.length}`);
    }
    
    if (selectedType !== '全部') {
      filtered = filtered.filter(record => record.type === selectedType)
    }
    
    this.setData({
      filteredRecords: filtered
    })
  },

  addRecord: function () {
    wx.navigateTo({
      url: '/pages/records/add/add'
    })
  },

  viewRecordDetail: function (e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/records/detail/detail?id=${id}`
    })
  }
}) 